const db = require('../db/db-connectivity')
const { requestVerify: verify } = require('../middleware/verify')
module.exports = {
  //获取商品列表
  getGoodsList: async (req, res, next) => {
    const { limit, offset = 5 } = req.query
    // const limit = parseInt(req.query.limit) //传过来的是带单引号的string'数值' 要把它转成number
    // const offset = 5 //通常只显示5条数据  不带limit则全部显示
    if (!limit) {
      const sqlStr = 'select * from goods'
      const [results] = await db.query(sqlStr)
      res.json({ goods: results, goodsCount: results.length })
    } else {
      const sqlStr = 'select * from goods limit ? offset ?'
      const [results] = await db.query(sqlStr, [
        Number.parseInt(limit),
        Number.parseInt(offset),
      ])
      res.json({ goods: results, goodsCount: results.length })
    }
  },

  //获取商品信息
  getGoodsByID: async (req, res, next) => {
    const goodId = req.params.goodId
    const sqlStr = 'select * from goods where good_id = ?'
    try {
      const [results] = await db.query(sqlStr, goodId)
      res.json({ goods: results, goodsCount: results.length }).end()
    } catch (error) {
      console.log(error)
    }
  },

  //获取商品种类
  getCategory: async (req, res, next) => {
    const sqlStr = 'select * from categories'
    try {
      const [results] = await db.query(sqlStr)
      res.json({ categories: results }).end()
    } catch (error) {
      console.log(error)
    }
  },

  /**
   * 提交订单内容
   */
  addOrdering: async (req, res, next) => {
    const order = req.body.ordering
    const nanoid = order.nanoid
    const createdTime = order.createdTime
    const cartItems = JSON.stringify(order.cartItems)
    const tableId = order.tableId
    const sqlStr =
      'insert into ordering SET nanoid=?,goodsList=?,createdTime=?,tableNum=?,mealNum=?'
    try {
      await db.execute(sqlStr, [
        nanoid,
        cartItems,
        createdTime,
        tableId,
        req.genNum,
      ])
      // res.status(200).end()
      res.send(req.genNum)
    } catch (error) {
      console.log(error)
      console.log('添加失败')
      return res.send('添加失败')
    }
  },

  tokenVerify: verify,
}
